package se.webbzon.boltzmann.game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import se.webbzon.boltzmann.debug.Debug;
import se.webbzon.boltzmann.game.environment.GameEnvironment;
import se.webbzon.oschi01.utilities.FileUtils;

public class LocalGame extends Game {
	
	// The file containing the local game
	private final File gameFile;
	
	/*============================================================
	Constructors
	============================================================*/

	public LocalGame(File gameFile) {
		super(FileUtils.removeExtension(gameFile.getName()));
		this.gameFile = gameFile;
	}
	
	public LocalGame(String name) {
		super(name);
		File gameFile;
		try {
			URI uri = LocalGame.class.getProtectionDomain().getCodeSource().getLocation().toURI();
			File runnableFile = new File(uri);
			File gameDirectory = new File(runnableFile.getParentFile(),"games");
			gameFile = new File(gameDirectory, getName() + ".bass");
		} catch (URISyntaxException e) {
			Debug.report(e);
			gameFile = null;
		}
		this.gameFile = gameFile;
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	@Override public boolean hasBackup() {
		return false;
	}

	@Override public Game getBackup() {
		return null;
	}

	@Override public GameEnvironment load(GameConfiguration config) throws Exception {
		if (gameFile != null) {
			if (gameFile.exists()) {
				FileInputStream fis = new FileInputStream(gameFile);
				GameEnvironment env = new GameReader().read(this, config, fis);
				fis.close(); 
				return env;
			} else {
				return createGame(config);
			}
		} else
			return createGame(config);
	}

	@Override public void save(GameEnvironment env) throws IOException {
		if (gameFile != null) {
			File directory = gameFile.getParentFile();
			if (!directory.exists())
				directory.mkdirs();
			if (!gameFile.exists())
				gameFile.createNewFile();
		
			FileOutputStream fos = new FileOutputStream(gameFile);
			new GameWriter().write(env, fos);
			fos.close();
		} else 
			throw new IOException("Could not write save game on local device.");
	}
	
	/** Removes the underlying file that contains this game. **/
	public boolean removeGame() {
		if (gameFile != null) {
			if (gameFile.exists())
				return gameFile.delete();
			else
				return true;
		} else
			return false;
	}
	
}
